package com.gtlab1207.br_security.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;

@Aspect
@Component
public class LoggerAdvice {
    private Logger logger = LoggerFactory.getLogger("access");

    @Pointcut("execution(* com.gtlab1207.br_security.ctrls..*(..))")
    private void logger(){}

    @Before("logger()")
    public void doBefore(JoinPoint jp) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpSession session = request.getSession();
        StringBuffer info = new StringBuffer();
        String method = request.getMethod();
        String ip = request.getHeader("X-Real-IP");
        info.append(ip).append(" ");
        info.append(request.getMethod()).append(" ");
        info.append(request.getRequestURI()).append(" ");
        if (method.equalsIgnoreCase("post") || method.equalsIgnoreCase("put")) {
            if (jp.getArgs().length > 0) {
                info.append(Arrays.toString(jp.getArgs()));
            }
        }
        logger.info(info.toString());
    }

    @Around("logger()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        Object object = pjp.proceed();
        return object;
    }
}
